<template>
	<view class="pb-150">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill">
		</image>
		<u-navbar title="电子通知" :autoBack="true" bgColor="transparent" :titleStyle="{ color: '#fff' }" safeAreaInsetTop
			placeholder leftIconColor="#fff"></u-navbar>

		<!-- 顶部筛选 -->
		<view class="search-filter-box">
			<view class="search-row">
				<u-search v-model="form1.title" placeholder="请输入通知标题/发布人姓名" @custom="getnoticelist"
					@search="getnoticelist"></u-search>
			</view>
			<view class="filter-row">
				<!-- <view class="filter-item">
					<text class="filter-label">发布时间</text>
					<view class="date-inputs">
						<view class="date-input-wrapper" @click="showStartPicker = true">
							<u--input v-model="query.start" placeholder="开始日期" readonly></u--input>
							<u-icon name="calendar" size="18" color="#999" class="calendar-icon" />
						</view>
						<text class="date-separator">至</text>
						<view class="date-input-wrapper" @click="showEndPicker = true">
							<u--input v-model="query.end" placeholder="结束日期" readonly></u--input>
							<u-icon name="calendar" size="18" color="#999" class="calendar-icon" />
						</view>
					</view>
				</view> -->
				<!-- <view class="filter-item">
					<text class="filter-label">状态</text>
					<view class="picker-input" @click="showStatusPicker = true">
						<text>{{ query.status || '请选择状态' }}</text>
						<u-icon name="arrow-down" size="18" color="#999" />
					</view>
				</view> -->
			</view>
			<!-- <view class="action-buttons">
				<u-button type="primary" size="small" @click="onSearch">查询</u-button>
				<u-button size="small" @click="onReset">重置</u-button>
			</view> -->
		</view>

		<!-- 列表 -->
		<view class="list-wrap">
			<view class="card" v-for="(item, idx) in list" :key="idx">
				<view class="card-hd">
					<view class="card-title"> <u-parse :content="item.title"></u-parse></view>
					<view :class="['badge', `level-${item.emergencyLevel}`]">{{ getUrgencyLabel(item.emergencyLevel) }}
					</view>
				</view>
				<view class="card-bd">
					<view class="row2">通知类型：{{ getNoticeTypeLabel(item.noticeType) }}</view>
					<!-- <view class="row2">发布人：{{ item.publisher }}</view> -->
					<!-- <view class="row2">状态：{{ item.status }}</view> -->
					<view class="row2">紧急程度：{{ getUrgencyLabel(item.emergencyLevel) }}</view>
					<view class="row2">是否需要回复：{{ item.needReply == 'N' ? '否' : '是' }}</view>
					<view class="row2 time">{{ item.createTime }}</view>
				</view>
				<view class="card-ft">
					<u-button v-if="item.status == 2 || item.status == -1" size="small" type="primary" plain
						@click="onEdit(item.noticeId)">编辑</u-button>
					<u-button size="small" type="error" plain @click="onDelete(item.noticeId)">删除</u-button>
				</view>
			</view>
			<view class="empty" v-if="filteredList.length === 0">
				<u-empty mode="data" icon="data" text="暂无通知"></u-empty>
			</view>
		</view>

		<view @tap="openDraft()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
			style="bottom: 68rpx;left: 30rpx;background: #0A993B;">
			发送通知
		</view>

		<!-- 选择器 -->
		<u-picker :show="showStartPicker" :columns="[yearOptions]" @confirm="onStartConfirm"
			@cancel="showStartPicker = false" @close="showStartPicker = false" />
		<u-picker :show="showEndPicker" :columns="[yearOptions]" @confirm="onEndConfirm" @cancel="showEndPicker = false"
			@close="showEndPicker = false" />
		<u-picker :show="showStatusPicker" :columns="[statusOptions]" @confirm="onStatusConfirm"
			@cancel="showStatusPicker = false" @close="showStatusPicker = false" />

		<!-- 起草通知弹框已替换为新页面 noticeEdit，原结构注释保留以便参考 -->

		<!-- 起草选择器 -->
		<u-picker :show="showTypePicker" :columns="[typeOptions]" @confirm="onTypeConfirm"
			@cancel="showTypePicker = false" @close="showTypePicker = false" />
		<u-picker :show="showLevelPicker" :columns="[levelOptions]" @confirm="onUrgencyConfirm"
			@cancel="showLevelPicker = false" @close="showLevelPicker = false" />

		<lsj-upload ref="lsjUploadRef"></lsj-upload>
		<u-safe-bottom></u-safe-bottom>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import {
	noticelist,
	delnoticedetail
} from '@/api/sylin/index.js'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			// ...existing code...
			urgencyOptions: [], // urgency 字典数据 {value,label}
			noticeTypeOptions: [], // sys_notice_type 字典数据
			query: {
				keyword: '',
				start: '',
				end: '',
				status: ''
			},
			showStartPicker: false,
			showEndPicker: false,
			showStatusPicker: false,
			showDraft: false,
			showTypePicker: false,
			showLevelPicker: false,
			yearOptions: (() => {
				const y = new Date().getFullYear();
				const a = [];
				for (let i = y + 5; i >= y - 10; i--) a.push(i.toString());
				return a;
			})(),
			statusOptions: ['全部', '已发', '草稿', '已撤销'],
			typeOptions: ['工作通知', '政策通知', '会议通知', '其它'],
			levelOptions: ['紧急', '一般', '普通'],
			levelText: {
				urgent: '紧急',
				normal: '一般',
				low: '普通'
			},
			list: [],
			// list: [{
			// 		title: '关于开展2024年春季森林防火工作的通知',
			// 		type: '工作通知',
			// 		publisher: '张三',
			// 		status: '已发',
			// 		time: '2024-05-10 15:23',
			// 		level: 'urgent'
			// 	},
			// 	{
			// 		title: '关于开展2024年春季森林防火工作的通知',
			// 		type: '政策通知',
			// 		publisher: '草梅',
			// 		status: '草稿',
			// 		time: '2024-05-10 15:23',
			// 		level: 'normal'
			// 	},
			// 	{
			// 		title: '关于开展2024年春季森林防火工作的通知',
			// 		type: '工作通知',
			// 		publisher: '张三',
			// 		status: '已发',
			// 		time: '2024-05-10 15:23',
			// 		level: 'low'
			// 	}
			// ],
			form: {
				title: '',
				type: '',
				level: '',
				content: '',
				fileName: '',
				receivers: []
			},
			uploadedFiles: [],
			form1: {
				pageNum: 1,
				pageSize: 99999,
				title: ''
			}
		}
	},
	onShow() {
		this.getnoticelist()
	},
	onLoad(options) {
		this.getnoticelist()
		this.getNoticeTypes()
		this.getUrgencyTypes()
		// if (options && (options.openAdd === '1' || options.openAdd === 1)) {
		// 	this.openDraft()
		// }
	},
	computed: {
		filteredList() {
			return this.list.filter(item => {
				if (this.query.keyword && this.query.keyword.trim()) {
					const k = this.query.keyword.trim().toLowerCase();
					const t = `${item.title}${item.publisher}${item.type}`.toLowerCase();
					if (!t.includes(k)) return false;
				}
				if (this.query.start) {
					const y = item.time.substring(0, 4);
					if (y < this.query.start) return false
				}
				if (this.query.end) {
					const y = item.time.substring(0, 4);
					if (y > this.query.end) return false
				}
				if (this.query.status && this.query.status !== '全部') {
					if (item.status !== this.query.status) return false
				}
				return true
			})
		}
	},
	methods: {
		async getUrgencyTypes() {
			try {
				const res = await this.getDicts('urgency')
				this.urgencyOptions = (res.data || []).map(d => ({ value: d.dictValue, label: d.dictLabel, listClass: d.listClass }))
			} catch (e) {
				console.error('获取紧急程度字典失败', e)
			}
		},
		getUrgencyLabel(emergencyLevel) {
			if (!emergencyLevel) return ''
			const item = this.urgencyOptions.find(i => i.value == emergencyLevel)
			return item ? item.label : emergencyLevel
		},
		async getNoticeTypes() {
			try {
				const res = await this.getDicts('notice_type')
				// 期望 res.data 是数组: [{dictValue, dictLabel}]
				this.noticeTypeOptions = (res.data || []).map(d => ({ value: d.dictValue, label: d.dictLabel }))
			} catch (e) {
				console.error('获取通知类型字典失败', e)
			}
		},
		getNoticeTypeLabel(noticeType) {
			// noticeType 为后端返回的字典 value
			if (!noticeType) return ''
			const item = this.noticeTypeOptions.find(i => i.value == noticeType)
			return item ? item.label : noticeType
		},
		async getnoticelist() {
			console.log(111)
			const res = await noticelist(this.form1)
			console.log(res)
			this.list = res.rows
		},
		onReset() {
			this.query = {
				keyword: '',
				start: '',
				end: '',
				status: ''
			}
		},
		onStartConfirm(e) {
			this.query.start = e.value[0];
			this.showStartPicker = false
		},
		onEndConfirm(e) {
			this.query.end = e.value[0];
			this.showEndPicker = false
		},
		onStatusConfirm(e) {
			this.query.status = e.value[0];
			this.showStatusPicker = false
		},
		openDraft() {
			uni.navigateTo({ url: '/pages/workbench/01task/noticeEdit' })
		},
		onTypeConfirm(e) {
			this.form.type = e.value[0];
			this.showTypePicker = false
		},
		onUrgencyConfirm(e) {
			this.form.level = e.value[0];
			this.showLevelPicker = false
		},
		handleUpload() {
			this.$refs.lsjUploadRef.chooseFile({
				count: 5,
				size: 20,
				formats: 'pdf,doc,docx,xlsx,xls,png,jpg',
				success: (files) => {
					files.forEach(file => {
						file.status = 'pending';
						this.uploadedFiles.push(file);
						this.uploadFile(file);
					})
				},
				fail: () => {
					uni.showToast({
						title: '选择文件失败',
						icon: 'none'
					})
				}
			})
		},
		uploadFile(file) {
			// 替换为后端上传地址
			const uploadUrl = 'https://your-upload-api.com/upload';
			this.$refs.lsjUploadRef.upload({
				url: uploadUrl,
				file: file,
				name: 'file',
				method: 'post',
				header: {},
				formData: {
					module: 'notice'
				},
				onprogress: (e) => {
					file.status = 'progress';
					file.progress = Math.round(e.progress)
				},
				success: (e) => {
					file.status = 'success';
					file.responseText = e.data;
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
				},
				fail: () => {
					file.status = 'fail';
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				}
			})
		},
		removeFile(index) {
			const file = this.uploadedFiles[index];
			if (file.status === 'progress') this.$refs.lsjUploadRef.abort(file);
			this.uploadedFiles.splice(index, 1)
		},
		publish() {
			if (!this.form.title) {
				return uni.showToast({
					title: '请输入标题',
					icon: 'none'
				})
			}
			uni.showToast({
				title: '已发布',
				icon: 'success'
			});
			this.showDraft = false
		},
		saveDraft() {
			uni.showToast({
				title: '草稿已保存',
				icon: 'success'
			});
			this.showDraft = false
		},
		resetForm() {
			this.form = {
				title: '',
				type: '',
				level: '',
				content: '',
				fileName: '',
				receivers: []
			}
		},
		onEdit(id) {
			uni.navigateTo({ url: `/pages/workbench/01task/noticeEdit?id=${id}` })
		},
		onDelete(id) {
			console.log(id)
			uni.showModal({
				title: '删除确认',
				content: '确定要删除该通知吗？',
				success: async res => {
					if (res.confirm) {
						const res = await delnoticedetail(id)
						console.log(res)
						this.getnoticelist()
						uni.showToast({
							title: '已删除',
							icon: 'success'
						})
					}
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 1;
}

.search-filter-box {
	background: #fff;
	margin: 20rpx;
	padding: 30rpx;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.search-row {
	margin-bottom: 20rpx;
}

.filter-row {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	margin-bottom: 16rpx;
}

.filter-item {
	display: flex;
	align-items: center;
}

.filter-label {
	width: 160rpx;
	font-size: 28rpx;
	color: #666;
	flex-shrink: 0;
}

.date-inputs {
	display: flex;
	align-items: center;
	flex: 1;
	gap: 16rpx;
}

.date-input-wrapper {
	position: relative;
	flex: 1;
}

.calendar-icon {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	pointer-events: none;
}

.date-separator {
	color: #999;
	font-size: 26rpx;
}

.picker-input {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #f8f9fa;
	padding: 16rpx;
	border-radius: 12rpx;
	color: #333;
	font-size: 28rpx;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
}

.action-buttons .u-button {
	flex: 1;
}

.list-wrap {
	margin: 20rpx;
}

.card {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.card-hd {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.card-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
}

.badge {
	padding: 8rpx 20rpx;
	border-radius: 24rpx;
	color: #fff;
	font-size: 22rpx;
}

.level-urgent {
	background: #ff4d4f;
}

.level-normal {
	background: #f4b400;
}

.level-low {
	background: #9e9e9e;
}

.card-bd {
	margin-top: 10rpx;
	color: #666;
}

.row2 {
	font-size: 24rpx;
	margin-top: 6rpx;
}

.time {
	color: #999;
}

.card-ft {
	margin-top: 12rpx;
	display: flex;
	gap: 16rpx;
	justify-content: flex-end;
}

.empty {
	padding: 80rpx 0;
}

/* 起草弹框 */
.draft-modal {
	background: #fff;
	border-radius: 18rpx;
	overflow: hidden;
}

.draft-hd {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 26rpx 24rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.draft-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.draft-bd {
	padding: 24rpx;
	max-height: 900rpx;
	overflow-y: auto;
}

.form-row {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.form-label {
	width: 140rpx;
	color: #666;
	font-size: 26rpx;
}

.select-input {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #f8f9fa;
	padding: 16rpx;
	border-radius: 12rpx;
	color: #333;
}

.file-name {
	margin-left: 16rpx;
	color: #666;
	font-size: 24rpx;
}

.tree-wrap {
	flex: 1;
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 12rpx;
}

.tree-node {
	padding: 8rpx 12rpx;
}

.draft-ft {
	padding: 20rpx 24rpx 26rpx;
	border-top: 1rpx solid #f0f0f0;
	display: flex;
	gap: 16rpx;
}

.draft-ft .u-button {
	flex: 1;
}
</style>